import { useRootStore } from "@/store";
import { proxyToObject } from "@/utils";
import { observer } from "mobx-react-lite";
import { useEffect, useState } from "react";

const AuthWrapper = (props: { children: JSX.Element, auth: string[] }) => {
    let { children, auth } = props;
    let { permissions } = useRootStore();
    const [flag, setFlag] = useState<boolean>(false);

    useEffect(() => {
        let buttonBox = proxyToObject(permissions.buttonPermissions);
        let isFlag = dealButtonAuth(buttonBox, auth);
        setFlag(isFlag);
    }, [permissions.buttonPermissions]);

    //处理权限是否存在
    const dealButtonAuth = (list: string[], auth: string[]): boolean => {
        if (!list || list.length == 0) return false;
        if (!auth || auth.length == 0) return false;
        const isFlag = list.some(permission => {
            return auth.includes(permission);
        })
        return isFlag;
    };
    return (
        <>
            {
                flag && children
            }
        </>
    )
}

export default observer(AuthWrapper)